%----------------------------------------------------------------
%  File    :  document.tex
%  Author  :  cja, sfe
%  Created :  30 June 2010
%  Changed :  30 June 2010
%
% Based on template by Keith Andrews. Thanks!
%----------------------------------------------------------------

\documentclass[10pt,twocolumn]{article}

\usepackage[          % set page and margin sizes
  a4paper,
  twoside,
  top=4mm,
  bottom=8mm,
  inner=15mm,
  outer=15mm,
  bindingoffset=0mm,
  head=10mm,
  foot=10mm,
  headsep=15mm,
  footskip=15mm,
  includeheadfoot, 
]{geometry}
% A4 is         210 x 297 mm
% want block of 180 x 235 mm
\setlength{\columnsep}{8.5mm}
\usepackage{balance}
\usepackage{times}                % use PostScript fonts
\usepackage[utf8]{inputenc}       % allow direct input of special chars
\usepackage{textcomp}             % symbols such as \texttimes and \texteuro
\usepackage[bf,sf]{titlesec}
\usepackage[
  position=bottom,
  margin=1cm,
  font=small,
  labelfont={bf,sf},
  format=hang,
  indention=0mm,
]{caption,subfig}

%% add if necessary: %%
\hyphenation{op-tical net-works semi-conduc-tor}

\usepackage{relsize}
\usepackage{tabularx}
\usepackage{listings}
\lstset{numbers=left, frame=single, captionpos=b, 
		breaklines=true, tabsize=2,basicstyle=\footnotesize,numbersep=5pt,
		language=Ruby}
\usepackage[hyphens,obeyspaces]{url}
\def\UrlFont{\small\ttfamily}
\renewcommand{\url}[1]
{
{% \def\UrlFont{\small\ttfamily}%
\begingroup \Url{#1}
}%
}
\usepackage{color}
\definecolor{darkgreen}{rgb}{0,0.3,0}
\definecolor{darkblue}{rgb}{0,0,0.2}
\definecolor{darkred}{rgb}{0.5,0,0}
\definecolor{lightgrey}{rgb}{0.8,0.8,0.8}
\definecolor{black}{rgb}{0,0,0}

\usepackage{ifpdf}
\ifpdf
  % pdflatex
  \usepackage[pdftex]{graphicx}
  \DeclareGraphicsExtensions{.pdf,.jpg,.png}
  \pdfcompresslevel=9
  \pdfpageheight=297mm
  \pdfpagewidth=210mm
  \usepackage[         % hyperref should be last package loaded
    pdftex,
    pdftitle={Effectively monitoring a Server over Secure Connection},
    pdfsubject={The application CpuStatistics},
    pdfauthor={Carina Janda, Stefan Fedl},
    bookmarks,
    bookmarksnumbered,
    linktocpage,
%    pagebackref,
    colorlinks,
    linkcolor=black,
    anchorcolor=black,
    citecolor=black,
    urlcolor=black,
    pdfview={FitH},
    pdfstartview={Fit},
    pdfpagemode=UseOutlines,       % open bookmarks in Acrobat
    plainpages=false,              % avoids duplicate page number problem
    pdfpagelabels,                 % avoids duplicate page number problem
  ]{hyperref}

\else
  % latex
  % should never have to run latex, since l2h now understands pdflatex .aux
  \usepackage[dvips]{graphicx}
  \usepackage[dvips]{hyperref}
  \DeclareGraphicsExtensions{.eps}
\fi
% IEEE specific names

\newcommand{\isbn}[1]
{
{\small
\href{http://www.amazon.com/exec/obidos/ASIN/#1/}{#1}%
}%
}


% DOIs  http://www.doi.org/  e.g.
% doi:10.1038/nature723
% http://dx.doi.org/10.1038/nature723
\newcommand{\doi}[1]
{
{\def\UrlFont{\rmfamily}
\href{http://dx.doi.org/#1}{\protect\nolinkurl{doi:#1}}%
}%
}


% based on url package
% define styles for class, file, and variable names
% which break nicely at line breaks
\newcommand\cname{\begingroup \small\urlstyle{tt}\Url}
\newcommand\fname{\begingroup \small\urlstyle{tt}\Url}
\newcommand\vname{\begingroup \small\urlstyle{tt}\Url}
\newcommand\email{\begingroup \small\urlstyle{tt}\Url}
\newcommand{\halfh}{9.5cm}        % height of figures for 2 per page
\newcommand{\thirdh}{6cm}         % height of figures for 3 per page
\date{}



\begin{document}


\title{
\sffamily\bfseries
Effective Server Monitoring for Clients\\
over a Secure Connection
}

\author{
{\large\bfseries Carina Janda} \\
{\smaller Advanced Security Engineering} \\
{\smaller FH JOANNEUM} \\
{\smaller Kapfenberg, Austria} \\
\email{carina.janda.ase09@fh-joanneum.at}
\and
{\large\bfseries Stefan Fedl} \\
{\smaller Advanced Security Engineering} \\
{\smaller FH JOANNEUM} \\
{\smaller Kapfenberg, Austria} \\
\email{stefan.fedl.ase09@fh-joanneum.at}
}


\maketitle
\thispagestyle{empty}
\pagestyle{empty}


\begin{abstract}
Server monitoring tools are widely known, used and popular. Most of them are
only accessable/usable ``directly'' on the machine which requires telnet
access or similar.\\
This paper introduces an application that behaves different:\\
Its server part runs on the target machine, giving only authenticated clients
the possibility to retrieve server data. This hardware information can be used
by clients for statistical analysis which is crucial for performance analysis
of business-critical server processes.\\
To ensure effectiveness, the server has full control over what connecting
clients receive. All returned values to the clients are pre-calculated.
Therefore a client cannot cause unexpected higher server load.\\
As this tool should be used in a productive manner, privacy and security
is ensured by keeping the whole transmission encrypted using RMI over SSL.
Platform independence is given using Java.\\
Analyzing hardware can be very valuable for server admins, therefore the tool
``cpustatistics'' was developed.
\end{abstract}

\section{INTRODUCTION}
Current possibilities fetching hardware data of business-critical server machines
are very limited. Those several limitations of tools like e.g. ``Nmon''
\cite{NMON} or ``top'' \cite{top} were the reason and the motivation for
designing a tool/application which provides a solution for the following
issues/problems:\\
(1) In normal cases, users or mainly administrators have the sole possibility to
connect directly to the machines and start the monitoring tools there via issuing
commands directly. (2) Direct connections to machines (normally via telnet) are
dangerous if not/unless encrypted. (3) Even if encrypted, users have to exactly
know what to do, especially on production systems. (4) There is still no
possibility to ``record'' those results over a specific period of time, e.g. in a
database, or display them in a proper way (GUI). ``Nmon'' provides a textual view
which cannot be called a GUI (but at least exported to .gif and .csv, see
\cite{NMON}. (5) Tools on server machines do not provide platform-independence. A
good tool should be useable from each (client-)machine that runs Java regardless
which operating system the server runs/has. (6) As the application should mainly
be usable on production machines, it must be well designed and implemented in the
matter of performance and security. (7) All that should be possible for the world
- always being at the latest development state - via a source code management
system.\\ We were sure to achieve these goals with the architecture and
technology that will be described in the following sections. In the
prototype-section, a closer look at the real implementation results is taken and
also the results are there illuminated.

\section{RELATED WORK}\label{sec:relatedWork}
During design and development of the application, much new knowledge has been
gained. Choosing a new way of managing source code was the first challenge for
the development team. Compared to older and traditional systems like CVS
\cite{CVS} and SVN \cite{Subversion}, Mercurial \cite{Mercurial} works different
- it belongs to the family of distributed versioning systems allowing several
parties commiting and pulling between their local repositories simultaneously.
The maybe more popular one is GIT \cite{GIT} which works after the same
principle. Especially in combination with the Eclipse-Plugin HgEclipse
\cite{MercurialEclipse}, mercurial is a very powerful tool which is also used at
large software projects like
NetBeans \cite{MercurialRepositoryNetBeans} or OpenJDK \cite{MercurialRepositoryJDK7}.\\
Another nice perception was that Java provides an own security API, called the
``Java Secure Socket Extension'' \cite{JSSE}. It provides powerful (and common)
security functions in an easy and straigt-forward way. Therefore it contains
hashing, encrypting and decrypting functions, also implementing well known
algorithms like the Advanced Encryption Standard (AES) \cite{AES} or the famous
hashing method MD5 \cite{MD5}. Both are necessary for the
prototype implementation. Using Java between different platforms, encoding'srelevance increases making UTF-8 \cite{Unicode} indispensable.\\
Getting started with JSSE \cite{JSSE_GettingStarted}, also a secure approach toRMI \cite{RMI} was implemented like in the JSSE-Example \cite{RMI_JSSE_Samples} with a Secure Socket Layer (SSL, \cite{SSL}).
As can also be seen in the results section \ref{sec:prototype}, trust- (certificationauthority) and key stores have an important role in this game, but they are
very tricky at the first usage/implementation attempt. RMI using a security manager witha mandatory policy file can be seen in that section which was tricky as well.\\
Another interesting and crucial fact for RMI development is that ``pure'' RMI isvulnerable to simple attacks by releasing too much information like stacktraces or stub names to the attacker \cite{SecurityAssessingJavaRMI}.
\section{MATERIALS AND METHODS}
The general approach to the prototype was very common: There was a
(1) Survey phase evaluting the current and state-of-the-art technologies,
(2) a concept/design phase using the evaluated results,
(3) a prototype phase which equals the design phase implemented in a prototype and
(4) a testing phase which actually tests the prototype and delivers a proof of concept if the tests were successful.\\
In ``reality'', these phases are more fine-grained and were divided up into several subsections.
Furthermore, there are some more things to consider, especially between phases:\\
- Possible design flaws as well as technology problems will already arise between conception and implementation phase.\\
- In case of the latter, the concept and the design phase will be applied alternatively.\\
- The testing phase seems to be an ongoing process throughout the whole project - from the first prototype to the last (possible) final release.\\
- Also the testing phase is the most crucial one: Outcomes of this phase are able to decide whether the chosen design can really be used for that
use case/implementation and how the prototype really performs and is e.g. both, secure and effective (performance).\\
These results and how the descicions in the concrete phase were really done can be read in the next section.

\section{RESULTS}
The concrete problem approach was done in the following order/steps:\\
(1) Survey: Choosing the implementation language. As Java is well known by both team members and the application should also be supported by
all platforms, it was the (clear) choice.\\
(2) Survey: The current available and state of the art technology in the Java field was evaluated.
Sockets and RMI were considered the most, no asynchronous messaging systems like JMS \cite{JMS} was meaningful for this usecase.\\
(3) Survey: The most appropriate one was chosen for the usecase:
As sockets use permanent connections which seems to be unsecure, RMI was chosen which always re-creates a socket at each remote call.\\
(4) Design: Based on that evaluation/survey, a proper design was created in the concept phase (written and drawed on paper first).
This design can be seen in figure \ref{fig:architecture}.\\
(5) Design: Use cases for each state of the prototype in the application were written. This enables the developer
to see possible problems earlier as they may have been considered before.\\
(6) Design: Drafts of a later possible graphical user interface (GUI) were handwritten (painted on paper).\\
(7) Implementation: The source code management system was set up as well as the google code page.\\
(8) Implementation: The design was implemented also by using the JSSE getting started guides \cite{JSSE_GettingStarted}.
At this phase, it was already plain to see that the design phase was well-considered and easy to implement.
There were only drawbacks which mainly effected performance and usability.\\
(9) Testing: What was (contineously) tested here was the implementation itsself, security assessments, user- and common errors (e.g. input validation).
As both team members have productive testing possibilities, it is also possible to test the application thouroughly in the matter of performance.
We now come to implementation details, and how the concept looked like in technical detail.
Not all of the concepts could be applied on the initial prototype; also problems are outlined, e.g. what has been forgotten in design phase.

\subsection{Concept}\label{sec:concept}
The previously mentioned implementation details start with three different and separated projects.
This enables the developer to determine clear borders between implementation classes and their responsibilites.
Also the client- and server functionality is completely independent from each other as e.g. classes from the client project cannot call/use
classes from the server project and vice versa. The whole architecture can be seen in figure \ref{fig:architecture}.
\begin{figure}[tp]
\centering
\includegraphics[keepaspectratio,width=\hsize]
{drawings/architecture_bigPicture.png}
\caption{Design and architecture illustration of the prototype stating the whole functionality in general.}
\label{fig:architecture}
\end{figure}
The next section will cover the whole theoretical idead behind this concept and also desribe the architecture more detailed.

\subsubsection{General}\label{sec:general}
Occurences in this section the application should support in general and cannot be applied/limited on one single project:\\
- 2-Tier architecture using really separated eclipse projects that cannot directly access each other which simulates authentic client/server-behaviour already at implementation\\
- A build system using ANT \cite{ANT} resulting in client.jar, common.jar and server.jar\\
- Automated unit tests using JUnit \cite{JUnit}, directly embedded in the build\\
- Object relational mapping using Hibernate \cite{Hibernate} enabling developers easily exchanging working database by configuration (JPA: Java Persistence API \cite{JPA})\\
- Extensibility of the whole prototype if another hardware information shall be added (e.g. HDD) and processed by the system automatically

\subsubsection{Performance}\label{sec:performance}
These could also count to the general section, but it's more obvious if there are issues that should be implemented in the matter of performance:\\
- Database- and disk access only if necessary, not if e.g. wrong input was supplied by user. Don't do checks over database(-queries)\\
- Lazy database access. Try to cache database access and do database operations at a time to minimize additional system load by the prototype\\
- Let clients only request server for new hardware values but do not really fetch hardware values triggered by the client. This item is also described in the 
server section \ref{sec:server}\\
- Limit rows that are allowed to be fetched from database (e.g. during export/statistics) 

\subsubsection{Security}\label{sec:security}
Again the separation in an own section focussing security the prototype should support:\\
- Secure connections over RMI implementing the SSL-standard using predefined socket factories. Trust- and keyStores for arriving clients\\
- Secure and controlled access using a SecurityManager together with a policy file. Each single permission has to be listed there separately with its allowed actions.\\
- Provide a common user authentication preventing that each client is allowed to fetch hardware data from server\\
- Input checks wherever possible (user input), defensive programming.\\
- Remove or null objects as soon as possible, e.g. at password fields\\
- Hash passwords in an unicode way in order to definitely let applications on different platforms create the same hashes (default charset varying)\\
- Use stored procedures in order to prevent SQL injections
\\
\\
Now each concrete implementation part is introduced in detail. Some features may have already been mentioned once; this was done on purpose as they cannot exactly be assigned
to one concrete section.

\subsubsection{Client}\label{sec:client}
The  client should be able to support the following criterias:\\
- One timer-thread refreshing data from the server\\
- One GUI-thread re-drawing the chart (background, via Swing framework, not self-implemented)\\
- Export being capable of both, exporting chart data as well as data from server-side database (statistics)\\
- Being connected to server (upon request) via RMI using SSL and a defined transport object\\

\subsubsection{Common}\label{sec:common}
The common part which is virtually but not indeed existent can just be described from an implementational point of view:\\
- Providing objects that both client and server have in common, e.g. the transport object which is the sole object responsible for client-server-transmission\\
- Providing an uniform interface, e.g. util-classes, also used for validation\\

\subsubsection{Server}\label{sec:server}
The server is responsible for noticeable more tasks than the client. The main thing is that everything on the server is organized in controllers to provide an easily maintainable
and centralized access, also in the matter of security:\\
- Provide a startup configuration for clients which contains initial values like the maximum polling interval a client is allowed to send server requests
for new hardware data (not visible on figure). Further config values meaningful\\
- One timer-thread saving the current hardware data into a database using Hibernate. The database is only accessed after a cache with a configurable
size is full. The whole cache is then written into the database and cleared at a time to save hard disk access/usage\\
- One thread accepting client connections and serving their requests on a specific port which should be configurable or handeled via parameters.
Threading is done in background and by RMI itsself via daemon threads\\
- One timer-thread fetching current hardware-data. This is done by a sole controller ``SigarController'' which is fully responsible for that task.
All the hardware information is fetched and controlled solely by this instance. Arriving clients do not trigger additional work,
they just receive the value that was recently fetched by the controller. This feature also fits in security \ref{sec:security} and performance section \ref{sec:performance}
\\
\\
In the following prototype section, several features from this concept section are picked out and described more detailed, providing some code listings as well.
In the end, there will be summarized which features the prototype does not cover.

\subsection{Prototype}\label{sec:prototype}

%% add missing link at the registry
Security and performance are main focusses of this prototype. At least the security issue in the matter of a secure connection can be easily established
by using a SslRMIClientSocketFactory as well as a SslRMIServerSocketFactory. Those instances are already implemented in the Java JDK 5 and just have to be passed
to a freshly created RMI registry which can be seen in listing \ref{lst:javaRegistrySecureSockets}
(note that creating stubs for clients automatically out of registry only works since Java 5)

\lstset{caption=''Creating a dummy RMI registry with a predefined secure client- as well as server socket'', label=lst:javaRegistrySecureSockets}
\begin{lstlisting}  
private void initSecureRMIRegistry() throws RemoteException {

    final int RMI_SERVER_PORT = 7711;
    final Registry registry = LocateRegistry.createRegistry(
    			RMI_SERVER_PORT,
    			new SslRMIClientSocketFactory(),
    			new SslRMIServerSocketFactory()
    );
    initComponents(registry);
}
\end{lstlisting} 

That's all about the security, at least concerning a secure transmission channel. Note that the ``LocateRegistry.createRegistry()''-method
throws a RemoteException, therefore it is mentioned in the example \ref{lst:javaRegistrySecureSockets}. The code is used in a very similar way in the prototype.
\\
It would have been too easy if there wasn't something missing: Using SSL also requires the usage of key- and truststores.
For the prototype implementation, the examples from JSSE \cite{RMI_JSSE_Samples} were chosen that clearly state virtual machine (VM) arguments
for the client as well as for the server.
The client needs to supply ``-Djavax.net.ssl.trustStore=samplecacerts -Djavax.net.ssl.trustStorePassword=changeit'' as VM argument,
the server ``-Djavax.net.ssl.keyStore=testkeys -Djavax.net.ssl.keyStorePassword=passphrase -Djava.security.policy=policy''.
As the commands may already say (that are exactly the ones of the prototype), the client requires a certification authority as well as a password
to access that trust store where the certificates are read from. ``samplecacerts'' could also be written as ``SampleCertifcationAuthorityCertificates''.
On the contrary, the server has to provide the key stores, and also the passphrase to access that store.
The last but not least term, the policy (and its location) has to be specified which will be talked about in the next paragraph.
Note that all these examples are just for demonstrating and testing purposes and should not be used in any productive manner.
Note also that to get SSL running with those arguments turned out to be a very annoying process,
therefore it's recommended to do that at the very end of the implementation phase.
\\
\\
What should also be considered to keep the server side secure is a security manager allowing only defined actions accessing the whole (file-)system.
These permitted entries are listed in a policy file which could look like that:

\lstset{caption=''Example policy file which makes system properties only accessible in a readable way'', label=lst:javaPolicyFile}
\begin{lstlisting}  
grant {
	permission
		java.util.PropertyPermission "*", "read";
};
\end{lstlisting} 

The above listing only allows System.getProperty() to be executed, not System.setProperty(). This information can also be gathered from JavaDoc of class PropertyPermission.
Note at this listing that a security manager has to be enabled to really use the policy file. A security manager activation for the whole JVM could look like
listing \ref{lst:javaSecurityManager}:

\lstset{caption=''Applying an RMISecurityManager to the whole JVM in order to (also) make use of policy files'', label=lst:javaSecurityManager}
\begin{lstlisting}  
if (System.getSecurityManager() == null) {
      System.setSecurityManager(
      	new RMISecurityManager()
      );
}
\end{lstlisting} 
We can say: A security manager together with a policy file can be a powerful combination. It enables the developer to totally narrow the access on a system
for each (Java-)code that is executed. From the development point of view, it is recommended to enable the security manager in a later implementation phase
(similar to the already mentioned SSL socket factories) as continuously adding permissions to the policy file can be really annoying and time consuming. Invalid code execution throws an
java.security.AccessControlException which is sometimes absolutely not ovbious due to long stack traces (``19 more\ldots''). This problem should especially be considered when
attempting to get Hibernate started with a security manager.
\\
\\
In order to come to the last security issue, it has to be said that ``normal'' security like it is expected by each program should not be forgotten.
(user) Input checking for null, min and max length are skipped at this point.
Passwords and all related instances should be nulled and cleared as soon as possible like it also happens in the prototype.
In addition, a password should be hashed with a (possibly) strong hash algorithm.
This can easily be done like illustrated in the following code example \ref{lst:javaMessageDigest}:

\lstset{caption=''Sample hashing method that could be used in e.g. a util class processing and returning byte arrays'', label=lst:javaMessageDigest}
\begin{lstlisting}  
public static byte[] toSHA1(final byte[] data) throws NoSuchAlgorithmException {

    final MessageDigest sha1MessageDigest = MessageDigest.getInstance("SHA-1");
    sha1MessageDigest.update(data);
    return sha1MessageDigest.digest();
}
\end{lstlisting}
In the protoype implementation, MD5 \cite{MD5} was used for general and testing
purposes of the MessageDigest class, but e.g. SHA512 \cite{SHA} would be much more appropriate due to a stronger algorithm (currently max. 512 bit)
and an already hacked and weak MD5.
It should may also be considered to instantiate the message digest only once, which saves handling of the NoSuchAlgorithmException for the caller, and
can also save performance as the sole message digest instance is always re-used, also at frequent calls
(the digest-method resets the messageDigest to its initial state, therefore this is possible). 
Note that the supplied paramater of the getInstance() method in listing \ref{lst:javaMessageDigest} is not case sensitive.
Note also that a byte array can easily be get out of a String calling String.getBytes().
More information can as usual be obtained from JavaDoc as well as the Java Cryptography Architecture (JCA, \cite{JCA}).
\\
In order to finally get an impression of the client GUI, the LoginFrame looks exactly like in figure \ref{fig:userLogin}.
\begin{figure}[tp]
\centering
\includegraphics[keepaspectratio,width=\hsize]
{drawings/login.png}
\caption{The initial client GUI displaying the login prompt for a user requiring a valid password}
\label{fig:userLogin}
\end{figure}
To finally get another impression of the client GUI, figure \ref{fig:chartStatistics} shows how hardware information is displayed on the client (part of the MainFrame).

\begin{figure}[tp]
\centering
\includegraphics[keepaspectratio,width=\hsize]
{drawings/chartStatistics.png}
\caption{The hardware information chart which is part of client application's main frame}
\label{fig:chartStatistics}
\end{figure}
To summarize which of the above features in the concept section \ref{sec:concept} are not part of the final prototype, consider the following listing:\\
- There are no serious and useful JUnit tests and as a result these tests are also not tested automatically by the build\\
- The results that are fetched from database are not limited concerning their max rows\\
- The cache size for the database timer is not configurable\\
- Hardware information can only be added by touching several classes, not by using simple extensibility\\
- Client- and server IP-addresses as well as port configuration is not configurable\\
- The SigarController was initially forgotten within the design. It was quite hard to redesign what happens if clients arrive with their requests.
\section{CONCLUSION and OUTLOOK}
The prototype is already at a state where it can be used productively. Especially its platform independence makes it attractive for non-server-admins
like developers to monitor system activity during process execution. In addition, users do not have to worry about performance or security issues on and to
the target system.\\
This paper also provides a look behind the scenes and shows how easily security and performance
mechanisms can be implemented with a formerly well considered design and straight-forward, easy to use implementation technologies
that already are there in the Java programming language.
Also the reader can be happy with further releases of the prototype implementing the missing things that are mentioned in the previous paragraph.
Always be up-to-date observing the google code page http://code.google.com/p/cpustatistics/. 
\bibliographystyle{kplain} 

\balance
% the bib entries are in file 'document.bib'
\bibliography{document}


\end{document}
